//辅助功能------------------------------------------------------------------------
/**
 * 视图渲染
 * @Param where 渲染位置
 * @Param templateName 模板名
 * @Param data 渲染数据
 * */
function viewToTemplate(where,templateName,data) {
    var html = $('script[type="text/'+templateName+'"]').html();//模板代码
    var arr=[];
    $("#"+where).html("");//清空tbody
    $.each(data, function (index, object) {
        arr.push(formatTemplate(object, html));
    });
    $("#"+where).append(arr.join(""));
}
function formatTemplate(object, tmpl,fun) {
    //m1 匹配到的字符{W} m2 字符的内容 W
    return tmpl.replace(/{(\w+)}/g,function (m1, m2) {
        if(!m2){
            return "";
        }
        if (typeof fun == 'function' ){
            fun();
        }
        return object[m2];
    })
}
/**
 * 价格改变
 * @param data
 * @returns {*}
 */
function priceAdopt(data) {
    for (var i=0;i <data.length; i++){
        data[i].onePrice /= 100;
    }
    return data;
}
//功能实现-----------------------------------------------------------------------------------------
/**
 * 渲染购物车视图
 */
function renderCartView(){
$.ajax({
    url:"/auth/queryShopping",
    type:"post",
    success:function (res) {
        if(res.code == "200"){
            var data = res.extend.shoppings
            priceAdopt(data)
            viewToTemplate("cart_view","cart_view",data)
            countPrice(data)
            countTotalPrice(data)
        }else {
            $("#cart_table").html(res.msg)
            $("#total_price_table").html("")
        }
    },
    error:function (res) {
        sweetAlert({
            title:"提示",
            text:"还没有登陆",
            type:"warning",
            showCancelButton:false,
            confirmButtonColor:"#dd6b55",
            closeOnConfirm:false
        },function () {
            window.location.assign("/login")
        })
    }
})
}

/**
 * 计算每行商品的总价格
 * @param data
 */
function countPrice(data){
    for(var i=0; i<data.length; i++) {
        var shopping = data[i];
        $("#single_totalPrice_"+shopping.shoppingId).html("￥"+shopping.num*shopping.onePrice+".00");
    }
}

/**
 * 计算总商品的价格
 * @param data
 */
function countTotalPrice(data){
    var total=0;
    for(var i=0; i<data.length; i++) {
        total += data[i].num * data[i].onePrice;
    }
    $("#total_price_tbody").html("")
    $("#total_price_tbody").append("<th>总价</th>\n" +
        "                           <td data-title=\"Subtotal\">\n" +
"                                        <span class=\"woocommerce-Price-amount amount\">\n" +
"                                        <span class=\"woocommerce-Price-currencySymbol\"></span>\n" +
        "价格：￥"+             total                           +".00\n" +
"                                         </span>\n" +
"                                     </td>")
}

/**
 * 购物车商品删除
 */
function delShoppingById(id) {
    sweetAlert({
        title:"是否删除",
        text:"你将无法更改!",
        type:"warning",
        showCancelButton:true,
        confirmButtonColor:"#dd6b55",
        closeOnConfirm:true
    },function (isConfired) {
        if(isConfired){
            $.ajax({
                url:"/auth/delShoppingById",
                type:"post",
                data:{"shoppingId":id},
                success:function (data) {
                    if(data.code == "200"){
                        sweetAlert("删除","商品已删除","success")
                        renderCartView();
                    }else {
                        sweetAlert("失败",data.msg,"error");
                    }

                }
            })
        }

    })
}
/**
 * 商品数量改变
 * @param obj
 */
function shoppingNumChange(obj) {
    var num=obj.value;
    if(num<0){
        alert("商品数量不能小于0");
        return ;
    }
    //获取购物车id
    var shoppingId=$(obj).attr("shoppingId");
    $.post({
        url:"/auth/updateShoppingNum",
        data:{"shoppingId":shoppingId,"num":num},
        success:function (data ) {
            if(num == 0) {
                $(obj).parent().parent().parent().remove();
            }
            renderCartView();
        },
        error:function (res) {
            sweetAlert({
                title:"提示",
                text:"还没有登陆",
                type:"warning",
                showCancelButton:false,
                confirmButtonColor:"#dd6b55",
                closeOnConfirm:false
            },function () {
                window.location.assign("/login")
            })
        }
    })
return ;
}
//预加载-------------------------------------------------------------------------------------------
/**
 * 初始化
 */
$(document).ready(function(){
    //获取购物车的信息
    renderCartView()
})